<?php

class PictureController extends \BaseController {

    public function getIndex() {
        return 'Index';
    }



    public function getUpload() {
        if(!Auth::check()) {
            return Redirect::to('/');
        } else {


            $Category = new Category;
            $renderCategories = $Category->getCategories(1, true);



            return View::make('front/upload')
                    ->with('renderCategories', $renderCategories);
        }
    }



    public function postUpload() {
        if(Auth::check()) {
            $userId = Auth::user()->id;
            $input = Input::all();

            $destinationPath = Config::get('app.picture_upload_path');

            $file = Input::file('files');
            $file = $file[0];



            $filename_thumb = str_random(32);
            $filename_middle = str_random(32);
            $filename_large = str_random(32);

            $fileExt = strtolower($file->getClientOriginalExtension());
            list($width, $height) = getimagesize($file);

            Image::make($file->getRealPath())->resize('400', null, function($constraint) {
                $constraint->aspectRatio();
            })->save($destinationPath . $filename_thumb . '.' . $fileExt);

            Image::make($file->getRealPath())->resize('800', null, function($constraint) {
                $constraint->aspectRatio();
            })->save($destinationPath . $filename_middle . '.' . $fileExt);

            Image::make($file->getRealPath())->save($destinationPath . $filename_large . '.' . $fileExt);

            $picture = new Picture();

            $picture->sku = "CNT-" . time();
            $picture->name = $input['name'];
            $picture->description = $input['description'];
            $picture->category_id = $input['category'];
            $picture->tags = $input['tags'];
            $picture->price = $input['price'];
            $picture->thumb = $filename_thumb . '.' . $fileExt;
            $picture->middle = $filename_middle . '.' . $fileExt;
            $picture->large = $filename_large . '.' . $fileExt;
            $picture->width = $width;
            $picture->height = $height;
            $picture->exif = $input['exifData'];
            $picture->user_id = $userId;
            $picture->license_type = $input['license_type'];
            //$picture->status = $input['status'];
            $picture->save();

            return Response::json('success', 200);

        } else {
            return Response::json('error', 401);
        }


    }

    //图片管理
    public function getManager() {
        if(Auth::check()) {

			if(Auth::user()->role == 1) {
				//超级管理员
				$pictures = Picture::orderBy('created_at', 'desc')->paginate(10);
			} else {
				//普通用户
				$userId = Auth::user()->id;
				$pictures = Picture::where('user_id', '=', $userId)->orderBy('created_at', 'desc')->paginate(10);
			}

            return View::make('front/photomanager')
                ->with('pictures', $pictures);
        }else {
            return Redirect::to('/');
        }
    }

    //图片删除
    public function getDelete($id) {
        if(Auth::check()) {
            $userId = Auth::user()->id;

            $picture = Picture::whereRaw('user_id = ? and id = ?', array($userId, $id))->delete();
            if($picture) {
                return Redirect::to('/picture/manager')
                    ->with('message', '成功删除一条记录！');
            }else {
                return Redirect::to('/picture/manager')
                    ->with('error', '删除失败！');
            }

        }else {
            return Redirect::to('/');
        }
    }

    //最新图片
    public function getFresh() {

        $pictures = Picture::paginate(20);
        foreach($pictures as $key => $picture) {
            $pictures[$key]->userInfo = User::find($picture->user_id);
            $pictures[$key]->exif = json_decode($pictures[$key]->exif);
        }
        return View::make('front/fresh')->with('pictures', $pictures)
										->with('keyword', '');
    }

    //图片信息
    public function getInfo($id) {
        $picture = Picture::find($id);
        $picture->userInfo = User::find($picture->user_id);
        $picture->exif = json_decode($picture->exif) == NULL?(object)array():json_decode($picture->exif);
        if(!property_exists((object)$picture->exif, 'Model')) {
            $picture->exif = array_merge((array)$picture->exif, array('Model' => '无此信息'));
        }
        if(!property_exists((object)$picture->exif, 'DateTimeDigitized')) {
            $picture->exif = array_merge((array)$picture->exif, array('DateTimeDigitized' => '无此信息'));
        }
        $picture->exif = (object)$picture->exif;

        $picture->tags = $picture->tags != ''?explode(',', $picture->tags):array();
        $picture->tags = (object)$picture->tags;

        return View::make('front/picture_preview')->with('picture', $picture);
    }

    //图片信息编辑
    public function getEdit($id) {
        //TODO AUTH
        $pictureInfo = Picture::find($id);

        $Category = new Category;
        $renderCategories = $Category->getCategories(1, true, $pictureInfo->category_id);

        return View::make('front/picture_edit')
            ->with('pictureInfo', $pictureInfo)
            ->with('renderCategories', $renderCategories);
    }

    public function postEdit() {
        //TODO AUTH

		if(Auth::check()) {

			$inputData = Input::all();

			$picture = Picture::find($inputData['picture_id']);

			if(Auth::user()->role == 1) {
				$picture->publish_index = Input::get('publish_index')? true : false;
			}

			$picture->name = $inputData['name'];
			$picture->description = $inputData['description'];
			$picture->category_id = $inputData['category_id'];
			$picture->tags = $inputData['tags'];
			$picture->price = $inputData['price'];
			$picture->save();

			return Redirect::to('/picture/manager');
		} else {
			return Redirect::to('/picture/manager');
		}
    }

    public function postSearch() {
		$keyword = Input::get('keyword');
		$pictures = Picture::whereRaw('name like ? or description like ? or tags like ?', array('%'. $keyword .'%', '%'. $keyword . '%', '%' . $keyword .'%'))->paginate(20);


        foreach($pictures as $key => $picture) {
            $pictures[$key]->userInfo = User::find($picture->user_id);
            $pictures[$key]->exif = json_decode($pictures[$key]->exif);
        }


        return View::make('front/fresh')
					->with('pictures', $pictures)
					->with('keyword', $keyword);
	}

}
